import sqlite3, re, os, sys, getopt, datetime
from support.utils.file.picture import Picture
from support.utils.dbms.db import DBHelper
from support.ui.console import Log

SUPPORT_FILE_TYPE = ['.jpeg','.png','.jpg','.mp4','.mov']
def printHelpInfo():
    print("幫助信息\n\n")
    print("usage: python {} [options] [db options]\n".format(sys.argv[0]))
    print("options:\n")
    print("-p\t : 从什么路径导入\n")
    print("-h\t : 帮助信息，与--help等效\n")
    print("db options:\n")
    print("--dbpath\t : 数据库存放路径，默认为脚本所在目录\n")
    print("--dbname\t : 数据库名字，默认为albuminfo.db\n")

def findDuplicateFiles(src, dbpath, dbname):
    pic = Picture(None)
    helper = DBHelper(dbpath, dbname)
    Log.i(__file__, "scan", src)
    if(src.upper().startswith("MTP")):
        walkMTPDevice()
    else:
        for path, dirlist, files in os.walk(src, followlinks=False):
            for file in files:
                subfile = os.path.join(path, file)
                if(os.path.isfile(subfile) and os.path.splitext(subfile)[-1].lower() in SUPPORT_FILE_TYPE):
                    ret = helper.query(DBHelper.TABLE_PICTURE, DBHelper.LOCAL, subfile)
                    if(not ret):
                        Log.i(__file__, subfile, "is a new file")
                        meta = pic.getMetaData(subfile, [Picture.KEY_GPS, Picture.KEY_WIDTH, Picture.KEY_HEIGHT, Picture.KEY_DATE])
                        _id = helper.insert(DBHelper.TABLE_ALBUM, {DBHelper.NAME:file, DBHelper.HASH:meta[Picture.HASH]})
                        helper.insert(DBHelper.TABLE_PICTURE, {DBHelper.ID:_id, DBHelper.LOCAL:subfile, DBHelper.WIDTH:pic.getData(meta,Picture.WIDTH), DBHelper.HEIGHT:pic.getData(meta,Picture.HEIGHT), DBHelper.DATE:pic.getData(meta,Picture.DATE)})
    helper.close()

if __name__ == "__main__":
    opts,args = getopt.getopt(sys.argv[1:], '-h-p:', ["help","dbpath=","dbname="])
    importfrom = None
    savepath = None
    dbpath = os.path.dirname(os.path.abspath(__file__))
    dbname = "albuminfo.db"
    Log.Level = Log.DEBUG
    #Log.Mode = Log.MODE_SYSTEM
    if(not opts):
        printHelpInfo()
        sys.exit()
    for opt_name, opt_value in opts:
        if(opt_name in ('-h','--help')):
            printHelpInfo()
            sys.exit()
        elif(opt_name == '-p'):
            importfrom = opt_value
        elif(opt_name == '--dbpath'):
            dbpath = opt_value
        elif(opt_name == '--dbname'):
            dbname = opt_value
    findDuplicateFiles(importfrom, dbpath, dbname)
